package com.example.springboot.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.example.springboot.common.exception.ServiceException;
import com.example.springboot.common.request.PageRequest;
import com.example.springboot.common.request.UserListRequest;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static com.example.springboot.common.exception.ExceptionConstant.Exists_UserName_ERROR;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 分页模糊查询
     * @param userListRequest
     * @return
     */
    public PageInfo<User> page(UserListRequest userListRequest) {
        PageHelper.startPage(userListRequest.getPageNum(), userListRequest.getPageSize());
        List<User> users = userMapper.listByCondition(userListRequest);
        return new PageInfo<>(users);
    }

    /**
     * 新增用户
     * @param user
     */
    public void save(User user) {
        // 判断用户名称是否已经存在
        if(userMapper.findByName(user.getName()) != null) {
            throw new ServiceException(Exists_UserName_ERROR);
        }

        // 为用户建立唯一卡号
        setOnlyCardNum(user);
        user.setUpdateTime(new Date());
        userMapper.save(user);
    }

    /**
     * 修改用户信息
     * @param user
     */
    public void update(User user) {
        // 判断用户名称是否已经存在
        if(userMapper.findByNameAndId(user) != null) {
            throw new ServiceException(Exists_UserName_ERROR);
        }

        user.setUpdateTime(new Date());
        userMapper.update(user);
    }

    /**
     * 根据id获取需要修改的用户信息
     * @param id
     * @return
     */
    public User getById(Integer id) {
        User user = userMapper.getById(id);
        return user;
    }

    /**
     * 根据id删除用户
     * @param id
     */
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    /**
     * 查询所有用户信息
     * @return
     */
    public List<User> list() {
        return userMapper.list();
    }

    /**
     * 批量删除用户信息
     * @param userIds
     */
    public void deleteBatch(Integer[] userIds) {
        userMapper.deleteBatch(userIds);
    }

    // 自动生成用户唯一卡号
    public void setOnlyCardNum(User user) {
        Date date = new Date();
        user.setCardNum(DateUtil.format(date, "yyyyMMdd") + Math.abs(IdUtil.fastSimpleUUID().hashCode()));
    }

}
